package com.oss.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.oss.PMF;
import com.oss.model.Site;
import com.oss.model.Link;

/**
 * @author xueqiang.mi
 * @since 2010-8-15
 */
public class SiteService extends BaseService {

	public void add(Site obj) {
		PersistenceManager pm = PMF.get();
		try {
			if (!isExist(obj.getUrl())) {
				pm.makePersistent(obj);
			}
		} finally {
			pm.close();
		}
	}

	public void extractAndAdd(Link obj) {
		String url = getSiteFromUrl(obj.getUrl());
		if (url != null) {
			String name = getDefaultSiteName(url);
			Site site = new Site(name, url);
			add(site);
		}
	}

	@SuppressWarnings("unchecked")
	private boolean isExist(String url) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Site.class);
			query.setFilter("url == :url");
			Collection<Link> c = (Collection<Link>) query.execute(url);
			if (c == null || c.isEmpty()) {
				return false;
			}
			return true;
		} finally {
			pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Site> getLatestSites(long pageIndex, long pageSize) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(Site.class);
			query.setOrdering("createdDate desc");
			query.setRange((pageIndex - 1) * pageSize, pageIndex * pageSize);
			Collection<Site> c = pm.detachCopyAll((Collection<Site>) query.execute());
			return new ArrayList<Site>(c);
		} finally {
			pm.close();
		}
	}

	public void delete(String id) {
		// TODO Auto-generated method stub

	}

}
